import 'dart:async';

/// 事件中心<br/>
/// Example:<br/>
/// ```dart
/// 注册单个事件
/// StreamSubscription<Event> subscription = eventCenter.subscribe('my.event').listen((event) {
///   // use data
///   dynamic data = event.data; // Outputs event values: 'this is data!'
/// });
///
/// 注册多个事件
/// StreamSubscription<Event> subscription = eventCenter.subscribe(['my.event','my.event1']).listen((event) {
///   switch(event.name){
///     case 'my.event':
///       break;
///     case 'my.event1':
///       break;
///   }
/// });
///
/// 取消注册，一般在dispose或者其他地方
/// subscription.cancel();
///
/// 发布事件
/// eventCenter.emit(Event('my.event',data: 'this is data!'));
/// ```
class EventCenter {

  late StreamController<Event> _eventStream;

  EventCenter._(){
    _eventStream = StreamController.broadcast();
  }

  /// 注册单个事件<br/>
  /// [name] 事件名
  Stream<Event> subscribe(String name) => _eventStream.stream.where((event) => event.name == name);

  /// 注册多个事件<br/>
  /// [names] 事件名集合
  Stream<Event> subscribes(List<String> names) => _eventStream.stream.where((event) => names.contains(event.name));

  /// 发布事件<br/>
  /// [event] 事件数据
  void emit(Event event){
    _eventStream.add(event);
  }
}

/// 全局单独的一个对象
EventCenter eventCenter = EventCenter._();

/// 事件信息
class Event{
  final String name;
  final dynamic data;

  Event(this.name, {this.data});
}